package com.splatter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chat.chatter.ejb.Emf;
import com.chat.chatter.ejb.Splat;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;


public class PostClip extends HttpServlet {
    private static final Logger log = Logger.getLogger(PostClip.class.getName());
	
	private static final long serialVersionUID = 1881413500711441953L;
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		String s = "";
		Enumeration e = req.getParameterNames();
		while ( e.hasMoreElements() ) {
			s = (String)e.nextElement();
			System.out.println("req.getParameterNames(): " + s);
		}
		System.out.println(req.getParameterValues("data"));

		String clip = req.getParameter("data");//s.substring(5, s.length()-1);//req.getParameter(s);//("data");
		if (clip == null) {
			clip = "(nada)";
		}
		System.out.println( "clip: " + clip );
		if (user != null) {
			//log.info("Greeting posted by user " + user.getNickname() + ": " + clip);
			System.out.println("Greeting posted by user " + user.getNickname() + ": " + clip);
		} else {
			//log.info("Greeting posted anonymously: " + content);
			System.out.println("Greeting posted anonymously: " + clip);
		}
		
		saveClip( "try", clip );
		
		//resp.sendRedirect("/postClip.jsp");
	}
	
	private void saveClip( String user, String clip ) {
		EntityManager em = Emf.get().createEntityManager();
		
		List existing = new ArrayList();
		
		try {
	        // ... do stuff with em ...
			if ( null == em ) {
                System.out.println( "entityManagerFactory is hosed" );
			}
			
		    existing = em.createQuery(
		    		"select u from User u where u.username = :username")
		    		.setParameter("username", user)
		    		.getResultList();

		    if ( existing.size() == 0 ) {
		    	System.out.println("!!!NO USER EXIST!!!");
		    }
		    else {
		    	System.out.println("User");
		    	System.out.println(existing);
		    	System.out.println("!!!USER EXIST!!!");
		    	if ( existing.size() == 1 ) {
		    		com.chat.chatter.ejb.User dbUser = ( com.chat.chatter.ejb.User )existing.get( 0 );
		    		
		    		if ( clip != null && dbUser != null ) {
			    		Blob text = new Blob( clip.getBytes() );
			    		Splat splat = new Splat();
			            splat.setSplat( text );
			            System.out.println("splat text val: " + splat.getSplat().toString() );
			            splat.setUser( dbUser );
			            em.persist( splat );
		    		}
		    	}
		    }
		} catch ( Exception e ) {
			System.out.println("PostClip kaboom!");
	    } finally {
	        em.close();
	    }
	    
	    String userName = "";
	    String name = "";
	    String password = "";
	    if ( existing.size() > 0 ) {
	    	userName = ( ( com.chat.chatter.ejb.User )existing.get( 0 ) ).getUsername();
		    name = ( ( com.chat.chatter.ejb.User )existing.get( 0 ) ).getName();
		    password = ( ( com.chat.chatter.ejb.User )existing.get( 0 ) ).getPassword();
		    System.out.println( "username: " + userName +
				       " name: " + name +
				       " password: " + password );
	    }
	}
	
}
